package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.feign.PermissionFeignService;
import org.mms.pojo.dto.PermissionDto;
import org.mms.pojo.dto.UserDto;
import org.mms.pojo.entity.Feedback;
import org.mms.pojo.entity.Permission;
import org.mms.pojo.entity.User;
import org.mms.pojo.request.FeedbackCreateRequest;
import org.mms.pojo.request.FeedbackReplyRequest;
import org.mms.pojo.util.ResponseMessage;
import org.mms.repository.FeedbackRepository;
import org.mms.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.mms.feign.UserFeignService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackRepository feedbackRepository;
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private PermissionFeignService permissionFeignService;

    @Override
    @Transactional(readOnly = true)
    public List<Feedback> list() {
        return feedbackRepository.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Feedback getById(Long id) {
        return feedbackRepository.findById(id)
                .orElseThrow(() -> new BusinessException("反馈记录不存在 (ID: " + id + ")"));
    }

    @Override
    @Transactional
    public Feedback create(FeedbackCreateRequest request) {
        // 远程调用获取用户
        ResponseMessage<UserDto> response = userFeignService.getById(request.getSubmitterId());
        if (response == null || response.isError()) {
            throw new BusinessException("提交用户不存在 (ID: " + request.getSubmitterId() + ")");
        }

        User submitter = User.fromDto(response.getData());
        if (submitter == null) {
            throw new BusinessException("提交用户不存在 (ID: " + request.getSubmitterId() + ")");
        }

        if (request.getContent() == null || request.getContent().trim().isEmpty()) {
            throw new BusinessException("反馈内容不能为空");
        }

        Feedback feedback = new Feedback();
        feedback.setContent(request.getContent());
        feedback.setSubmitter(submitter);

        return feedbackRepository.save(feedback);
    }

    @Override
    @Transactional
    public Feedback replyTo(FeedbackReplyRequest request) {
        Feedback feedback = feedbackRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("反馈记录不存在 (ID: " + request.getId() + ")"));

        ResponseMessage<UserDto> userResponse = userFeignService.getById(request.getReplierId());
        if (userResponse == null || userResponse.isError()) {
            throw new BusinessException("回复用户不存在 (ID: " + request.getReplierId() + ")");
        }

        User replier = User.fromDto(userResponse.getData());
        if (replier == null) {
            throw new BusinessException("回复用户不存在 (ID: " + request.getReplierId() + ")");
        }


        // 检查用户是否有 feedback_reply 权限
        ResponseMessage<List<PermissionDto>> permissionsResponse = permissionFeignService.getAll();
        if (permissionsResponse == null || permissionsResponse.isError()) {
            throw new BusinessException("用户没有回复反馈的权限 (ID: " + replier.getId() + ")");
        }

        List<Permission> permissions = permissionsResponse
                .getData()
                .stream()
                .map(Permission::convertFromDto)
                .toList();

        boolean hasReplyPermission = permissions.stream()
                .anyMatch(permission -> "feedback_reply".equals(permission.getPermissionKey()));

        if (!hasReplyPermission) {
            throw new BusinessException("用户没有回复反馈的权限 (ID: " + replier.getId() + ")");
        }

        if (request.getReply() == null || request.getReply().trim().isEmpty()) {
            throw new BusinessException("回复内容不能为空");
        }

        feedback.setReply(request.getReply());
        feedback.setReplier(replier);
        feedback.setReplyTime(LocalDateTime.now());

        return feedbackRepository.save(feedback);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if (!feedbackRepository.existsById(id)) {
            throw new BusinessException("无法删除：反馈记录不存在 (ID: " + id + ")");
        }
        feedbackRepository.deleteById(id);
    }
}